package cn.qiyu5522.tk_ems.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @BelongsProject: tk_ems
 * @BelongsPackage: cn.qiyu5522.tk_ems.handler
 * @Author: TangQi
 * @CreateTime: 2023-02-01  09:18
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 获取当前登录用户的编号
        Long loginId = null;
        String loginName = "";
        try {
            String loginInfo = (String) StpUtil.getLoginId();
            loginId = Long.valueOf(loginInfo.split("-")[0]);
            loginName = loginInfo.split("-")[1];
        } catch (Exception e) {
            // 异常 默认为管理员添加
            loginId = 1620600815042273282L;
            loginName = "admin";
        }
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "operatorId", Long.class, loginId);
        this.strictInsertFill(metaObject, "operator", String.class, "admin");
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.strictInsertFill(metaObject, "state", Integer.class, 0);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 获取当前登录用户的编号
        String loginInfo = (String) StpUtil.getLoginId();
        Long loginId = Long.valueOf(loginInfo.split("-")[0]);
        String loginName = loginInfo.split("-")[1];
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "operatorId", Long.class, loginId);
        this.strictInsertFill(metaObject, "operator", String.class, loginName);

    }
}
